<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/9/26 20:56
 */

namespace module\user\front\input;

use app\library\validate\CaptchaValidate;
use mof\exception\LogicException;
use mof\Request;

/**
 * 找回密码
 * @property string $type 找回方式
 * @property string $account 账号
 * @property string $password 新密码
 */
class ForgetInput
{
    const EMAIL  = 'email';
    const MOBILE = 'mobile';

    protected array $attrs = [
        'type', 'account', 'password'
    ];

    public function __construct(protected array $data)
    {
    }

    public static function __make(Request $request): static
    {
        $type = $request->post('type');
        if (static::EMAIL === $type) {
            $rules = [
                'account|邮箱'   => 'require|email',
                'captcha|验证码' => 'require|emsCaptcha:account,#forget',
            ];
            $message = [
                'account.require'    => '邮箱不能为空',
                'account.email'      => '邮箱格式不正确',
                'captcha.emsCaptcha' => '验证码不正确',
            ];
        } else if (static::MOBILE === $type) {
            $rules = [
                'account|手机号' => 'require|mobile',
                'captcha|验证码' => 'require|smsCaptcha:account,#forget',
            ];
            $message = [
                'account.require'    => '手机号不能为空',
                'account.email'      => '手机号格式不正确',
                'captcha.emsCaptcha' => '验证码不正确',
            ];
        } else {
            throw new LogicException('未知的找回方式');
        }
        $rules['password|新密码'] = 'require|min:5';
        $rules['confirmPassword|确认密码'] = 'require|confirm:password';

        CaptchaValidate::register();
        $data = $request->withValidate($rules, $message)->post();

        return new self($data);
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }
}